import globalData from '../utils/global.js'
import {
    toast,
    confirm,
    alert
} from '../utils/util.js'
import user from '../utils/user.js'

import { shark } from '../utils/util.js'

let requestList = 0
let errorStatus = false

export class Request {
    constructor(baseurl) {
        this.baseUrl = baseurl
    }

    /**
     * 
     * @param {*} object Request Object
     * @param {{isLoading: Boolean, isToast: Boolean}} config 
     * @returns 
     */
    all(object, config) {
        if (!/http/.test(object.url)) {
            object.url = this.baseUrl + object.url
        }
        if (config.isLoading !== false) {
            if (!requestList) {
                wx.showLoading({
                    mask: true,
                    title: '数据加载中'
                })
            }
            requestList += 1
        }

        if (typeof object.params === 'object') {
            let result = ''
            for (const item in object.params) {
                result += item + '=' + object.params[item] + '&'
            }
            result = result.slice(0, result.length - 1)
            if (result)
                object.url += (/\?/.test(object.url)) ? result : '?' + result
        }

        if (globalData.token && object.header)
            object.header.Authorization = 'Wx ' + globalData.token
        if (globalData.token && !object.header)
            object.header = {
                Authorization: 'Wx ' + globalData.token
            }

        return new Promise((reslove, reject) => {
            object.success = (res) => {
                if (res.statusCode === 200 && res.data.code === 401) {
                    shark(() => {
                        toast('登录超时，正在为您重新登录')
                        setTimeout(() => {
                            user.reLogin().then(() => {
                                wx.reLaunch({
                                    url: '/pages/index/index'
                                })
                            }, () => {
                                confirm('登录失败，请尝试重新打开小程序或联系管理员')
                            })
                        }, 1500)
                        return 0
                    })
                }
                if (res.statusCode > 300 || res.statusCode < 200 || res.data.code > 300 || res.data
                    .code < 200) {
                    wx.hideLoading({
                        complete() {
                            if (config.isToast !== false) {
                                if (res.data.msg && res.data.msg.length > 20) {
                                    alert(res.data.msg)
                                } else {
                                    toast(res.data.msg ? res.data.msg : '请求错误',  'none', 3000)
                                }
                            }
                        }
                    })
                    reject(res)

                    // 错误上报
                    // throw new Error(JSON.stringify({
                    //     url: object.url,
                    //     statusCode: res.statusCode,
                    //     method: object.method,
                    //     requestData: object.data,
                    //     responseData: res.data
                    // }))
                } else {
                    reslove(res)
                }
            }
            object.fail = (err) => {
                wx.hideLoading()
                if (!errorStatus) {
                    errorStatus = true
                    wx.hideLoading({
                        complete() {
                            if (config.isToast !== false)
                                toast(err.data ? err.data.error : '网络错误，请检查网络后重试')
                        }
                    })
                    errorStatus = false
                }
                console.log(err)
                reject(err)
            }
            object.complete = () => {
                if (config.isLoading !== false)
                    requestList -= 1
                if (requestList === 0) {
                    wx.hideLoading()
                }
            }
            wx.request(object)
        })
    }

    post(url, data, config = {}) {
        return this.all({
            url: url,
            params: config.params || {},
            data: JSON.stringify(data),
            method: 'post',
            header: {
                'content-type': 'application/json'
            }
        }, config)
    }

    get(url, data, config = {}) {
        return this.all({
            url: url,
            data: data,
            method: 'get',
        }, config)
    }

    put(url, data, config = {}) {
        return this.all({
            url: url,
            data: data,
            method: 'put',
        }, config)
    }

    delete(url, data, config = {}) {
        return this.all({
            url: url,
            data: data,
            method: 'delete',
        }, config)
    }


}

const request = new Request(globalData.baseUrl)
export default request